<!DOCTYPE html><html class="appearance-auto" lang="zh-CN"><head><meta charset="UTF-8"><title>【Spring源码解析系列】 Spring获取Bean</title><meta name="description" content="用创业者心态做好每一件事情！"><meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, initial-scale=1"><!-- Google Analytics --><!-- End Google Analytics -->
<!-- Baidu Analytics --><!-- End Baidu Analytics --><link rel="icon" href="/blog/images/favicon.png"><link rel="stylesheet" href="/blog/style/common/bulma.css"><link rel="stylesheet" href="/blog/style/base.css"><link rel="stylesheet" href="/blog/style/common/helper.css"><script src="/blog/js/common.js"></script><link rel="stylesheet" href="/blog/style/post.css"><link rel="stylesheet" href="/blog/style/themes/highlight-theme-light.css"><script src="/blog/js/highlight.pack.js"></script><meta name="description" content="
本文主要讲述Spring获取Bean过程


getBean位置：AbstractApplicationContext::getBean()在解析完配置获取应用上下文ApplicationContext之后便可以获取Bean对象，调用AbstractApplicationContext类中的getBean()方法即可。
@Override
public Object getBean(String name) throws BeansException &amp;#123;
    assertBeanFactoryActive();
    return getBeanFactory().getBean(name);
&amp;#125;

@Override
public &amp;lt;T&amp;gt; T getBean(Str.."><!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.1"><link rel="alternate" href="/blog/atom.xml" title="janedler's blog" type="application/atom+xml">
</head><body class="is-flex is-flex-direction-column"><header class="header-widget is-flex-shrink-0 is-hidden-mobile"><div class="container is-fullhd is-flex is-justify-content-space-between is-align-items-center is-full-height"><section class="is-hidden-mobile is-flex-shrink-0"><h2><a href="/blog/">田园牧歌(*︶*)'s blog</a></h2></section><h3 class="is-hidden-mobile is-family-serif is-full-height is-flex is-align-items-center is-flex-shrink-0"><div class="is-full-height" id="postTopic"><p class="is-full-height is-flex-shrink-0 is-flex is-align-items-center is-justify-content-center">【Spring源码解析系列】 Spring获取Bean</p><p class="is-full-height is-flex-shrink-0 is-flex is-align-items-center is-justify-content-center">点击返回顶部</p></div></h3><aside class="is-flex-shrink-0"><h3 class="is-inline-block"><a href="/blog/">首页</a></h3><h3 class="is-inline-block"><a href="/blog/about">关于</a></h3><h3 class="is-inline-block"><a href="/blog/archives">归档</a></h3></aside></div></header><header class="is-flex header-widget is-flex-shrink-0 is-align-items-center is-justify-content-center is-hidden-tablet"><h3 class="is-inline-block"><a href="/blog/">首页</a></h3><h3 class="is-inline-block"><a href="/blog/about">关于</a></h3><h3 class="is-inline-block"><a href="/blog/archives">归档</a></h3></header><main><main class="container is-max-widescreen content section post-page pt-4 px-4"><div class="columns is-flex-desktop is-justify-content-center is-flex-direction-row-reverse"><div class="column is-3 is-hidden-mobile"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#getBean"><span class="toc-text">getBean</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#doGetBean"><span class="toc-text">doGetBean</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Singleton%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">Singleton初始化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Prototype%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">Prototype初始化</span></a></li></ol></li></ol></div><div class="column is-9"><header class="my-4"><a href="/blog/tags/Java"><i class="tag post-item-tag">Java</i></a><a href="/blog/tags/Spring"><i class="tag post-item-tag">Spring</i></a></header><h1 class="mt-0 mb-1 is-family-serif" id="postTitle">【Spring源码解析系列】 Spring获取Bean</h1><time class="has-text-grey" datetime="2022-11-28T16:00:00.000Z">2022-11-29</time><article class="mt-2 post-content"><p><img src="https://janedler.oss-cn-beijing.aliyuncs.com/images/spring.png" alt="cover"></p>
<p>本文主要讲述Spring获取Bean过程</p>
<span id="more"></span>

<h2 id="getBean"><a href="#getBean" class="headerlink" title="getBean"></a>getBean</h2><p>位置：AbstractApplicationContext::getBean()<br>在解析完配置获取应用上下文ApplicationContext之后便可以获取Bean对象，调用<strong>AbstractApplicationContext</strong>类中的getBean()方法即可。</p>
<pre><code class="java">@Override
public Object getBean(String name) throws BeansException &#123;
    assertBeanFactoryActive();
    return getBeanFactory().getBean(name);
&#125;

@Override
public &lt;T&gt; T getBean(String name, Class&lt;T&gt; requiredType) throws BeansException &#123;
    assertBeanFactoryActive();
    return getBeanFactory().getBean(name, requiredType);
&#125;

@Override
public Object getBean(String name, Object... args) throws BeansException &#123;
    assertBeanFactoryActive();
    return getBeanFactory().getBean(name, args);
&#125;

@Override
public &lt;T&gt; T getBean(Class&lt;T&gt; requiredType) throws BeansException &#123;
    assertBeanFactoryActive();
    return getBeanFactory().getBean(requiredType);
&#125;

@Override
public &lt;T&gt; T getBean(Class&lt;T&gt; requiredType, Object... args) throws BeansException &#123;
    assertBeanFactoryActive();
    return getBeanFactory().getBean(requiredType, args);
&#125;
</code></pre>
<blockquote>
<p>通过先获取由obtainFreshBeanFactory()方法创建出来的BeanFactory，再调用其中的getBean()方法。</p>
</blockquote>
<pre><code class="java">@Override
public final ConfigurableListableBeanFactory getBeanFactory() &#123;
    DefaultListableBeanFactory beanFactory = this.beanFactory;
    if (beanFactory == null) &#123;
        throw new IllegalStateException(&quot;BeanFactory not initialized or already closed - &quot; +
                    &quot;call &#39;refresh&#39; before accessing beans via the ApplicationContext&quot;);
    &#125;
    return beanFactory;
&#125;
</code></pre>
<blockquote>
<p>最后通过调用AbstactBeanFactory中的doGetBean()方法来获取Bean；</p>
</blockquote>
<h2 id="doGetBean"><a href="#doGetBean" class="headerlink" title="doGetBean"></a>doGetBean</h2><p>位置：AbstractBeanFactory::doGetBean</p>
<pre><code class="java">//真正实现向IOC容器获取Bean的功能，也是触发依赖注入功能的地方
//如果Bean定义的单例模式（Singleton）,则容器在创建之前先从缓存中查找，以确保整个容器中只存在一个实例对象。
//如果Bean定义的是原型模式（Prototype），则容器每次都会创建一个新的实例对象。
//此源码只是定义了根据Bean定义的模式，采取不同的创建Bean实例对象的策略，具体的Bean实例对象的创建过程
//由实现了ObjectFactory接口的匿名内部类的createBean方法完成，ObjectFactory使用了委派模式，具体
//的Bean实例创建过程交由其实现类AbstractAutowireCapableBeanFactory完成。
@SuppressWarnings(&quot;unchecked&quot;)
protected &lt;T&gt; T doGetBean(
            String name, @Nullable Class&lt;T&gt; requiredType, @Nullable Object[] args, boolean typeCheckOnly)
            throws BeansException &#123;
    //根据指定的名称获取被管理Bean的名称，剥离指定名称中对容器的相关依赖
    //如果指定的是别名，将别名转换为规范的Bean名称
    String beanName = transformedBeanName(name);
    Object beanInstance;
    //先从缓存中取是否已经有被创建过的单态类型的Bean
    //对于单例模式的Bean整个IOC容器中只创建一次，不需要重复创建
    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = getSingleton(beanName);
    //IOC容器创建单例模式Bean实例对象
    if (sharedInstance != null &amp;&amp; args == null) &#123;
        if (logger.isTraceEnabled()) &#123;
            //如果指定名称的Bean在容器中已有单例模式的Bean被创建
            //直接返回已经创建的Bean
            if (isSingletonCurrentlyInCreation(beanName)) &#123;
                logger.trace(&quot;Returning eagerly cached instance of singleton bean &#39;&quot; + beanName +
                            &quot;&#39; that is not fully initialized yet - a consequence of a circular reference&quot;);
            &#125;
            else &#123;
                logger.trace(&quot;Returning cached instance of singleton bean &#39;&quot; + beanName + &quot;&#39;&quot;);
            &#125;
        &#125;
        //获取给定Bean的实例对象，主要是完成FactoryBean的相关处理
        //注意：BeanFactory是管理容器中Bean的工厂，
        //而FactoryBean是创建对象的工厂Bean，两者之间有区别
        beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    &#125;
    else &#123;
        // Fail if we&#39;re already creating this bean instance:
        // We&#39;re assumably within a circular reference.
        //缓存没有正在创建的单例模式Bean
        //缓存中已经有已经创建的原型模式Bean
        //但是由于循环引用的问题导致实例化对象失败
        if (isPrototypeCurrentlyInCreation(beanName)) &#123;
            throw new BeanCurrentlyInCreationException(beanName);
        &#125;
        // Check if bean definition exists in this factory.
        //对IOC容器中是否存在指定名称的BeanDefinition进行检查，首先检查是否能
        //在当前的BeanFactory中获取的所需要的Bean，如果不能则委托当前容器的父级
        //容器去查找，如果还是找不到则沿着容器的继承体系向父级容器查找
        BeanFactory parentBeanFactory = getParentBeanFactory();
        //当前容器的父级容器存在，且当前容器不存在指定名称Bean
        if (parentBeanFactory != null &amp;&amp; !containsBeanDefinition(beanName)) &#123;
            // Not found -&gt; check parent.
            //解析指定Bean名称的原始名称
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory abf) &#123;
                return abf.doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
            &#125;
            else if (args != null) &#123;
                // Delegation to parent with explicit args.
                //委派父级容器根据指定名称和显示的参数查找
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            &#125;
            else if (requiredType != null) &#123;
                // No args -&gt; delegate to standard getBean method.
                //委派父级容器根据指定名称和类型查找
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            &#125;
            else &#123;
                //委派父级容器根据指定名称和类型查找
                return (T) parentBeanFactory.getBean(nameToLookup);
            &#125;
        &#125;
        //创建的Bean是否需要进行类型验证，一般不需要
        if (!typeCheckOnly) &#123;
            //向容器标记指定的Bean已经被创建
            markBeanAsCreated(beanName);
        &#125;
        StartupStep beanCreation = this.applicationStartup.start(&quot;spring.beans.instantiate&quot;)
                    .tag(&quot;beanName&quot;, name);
        try &#123;
            if (requiredType != null) &#123;
                beanCreation.tag(&quot;beanType&quot;, requiredType::toString);
            &#125;
            //根据指定Bean名称获取其父级的Bean定义
            //主要解决Bean继承时子类合并父类公共属性问题
            RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
            // Guarantee initialization of beans that the current bean depends on.
            //获取当前Bean所有依赖Bean的名称
            String[] dependsOn = mbd.getDependsOn();
            //如果当前Bean有依赖Bean
            if (dependsOn != null) &#123;
                for (String dep : dependsOn) &#123;
                    if (isDependent(beanName, dep)) &#123;
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    &quot;Circular depends-on relationship between &#39;&quot; + beanName + &quot;&#39; and &#39;&quot; + dep + &quot;&#39;&quot;);
                    &#125;
                    //把被依赖Bean注册给当前依赖的Bean
                    registerDependentBean(dep, beanName);
                    try &#123;
                        //递归调用getBean方法，获取当前Bean的依赖Bean
                        getBean(dep);
                    &#125;
                    catch (NoSuchBeanDefinitionException ex) &#123;
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    &quot;&#39;&quot; + beanName + &quot;&#39; depends on missing bean &#39;&quot; + dep + &quot;&#39;&quot;, ex);
                    &#125;
                &#125;
            &#125;
            // Create bean instance.
            //创建单例模式Bean的实例对象
            if (mbd.isSingleton()) &#123;
                //这里使用了一个匿名内部类，创建Bean实例对象，并且注册给所依赖的对象
                sharedInstance = getSingleton(beanName, () -&gt; &#123;
                    try &#123;
                        //创建一个指定Bean实例对象，如果有父级继承，则合并子类和父类
                        return createBean(beanName, mbd, args);
                    &#125;
                    catch (BeansException ex) &#123;
                        // Explicitly remove instance from singleton cache: It might have been put there
                        // eagerly by the creation process, to allow for circular reference resolution.
                        // Also remove any beans that received a temporary reference to the bean.
                        //显示的从容器单例模式Bean缓存中清除实例对象
                        destroySingleton(beanName);
                        throw ex;
                    &#125;
                &#125;);
                //获取给定Bean实例对象
                beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            &#125;
            //IOC容器创建原型模式Bean实例对象
            else if (mbd.isPrototype()) &#123;
                // It&#39;s a prototype -&gt; create a new instance.
                //原型模式（Prototype）是每次都会创建一个新的对象
                Object prototypeInstance = null;
                try &#123;
                    //回调beforePrototypeCreation方法，默认的功能是注册当前创建的原型对象
                    beforePrototypeCreation(beanName);
                    //创建指定Bean对象实例
                    prototypeInstance = createBean(beanName, mbd, args);
                &#125;
                finally &#123;
                    //回调afterPrototypeCreation方法，默认的功能告诉IOC容器指定Bean
                    afterPrototypeCreation(beanName);
                &#125;
                //获取给定Bean的实例对象
                beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            &#125;
            //要创建的Bean既不是单例模式，也不是原型模式，则根据Bean定义资源中
            //配置的生命周期范围，选择实例化Bean的合适方法，这种在Web应用程序中
            //比较常用，如：request、session、application等生命周期（scope）
            else &#123;
                String scopeName = mbd.getScope();
                if (!StringUtils.hasLength(scopeName)) &#123;
                    throw new IllegalStateException(&quot;No scope name defined for bean &#39;&quot; + beanName + &quot;&#39;&quot;);
                &#125;
                Scope scope = this.scopes.get(scopeName);
                //Bean定义资源中没有配置生命周期范围，则Bean定义不合法
                if (scope == null) &#123;
                    throw new IllegalStateException(&quot;No Scope registered for scope name &#39;&quot; + scopeName + &quot;&#39;&quot;);
                &#125;
                try &#123;
                    //这里又使用了一个匿名内部类，获取一个指定生命周期范围的实例
                    Object scopedInstance = scope.get(beanName, () -&gt; &#123;
                        beforePrototypeCreation(beanName);
                        try &#123;
                            return createBean(beanName, mbd, args);
                        &#125;
                        finally &#123;
                            afterPrototypeCreation(beanName);
                        &#125;
                    &#125;);
                    //获取给定Bean的实例对象
                    beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                &#125;
                catch (IllegalStateException ex) &#123;
                    throw new ScopeNotActiveException(beanName, scopeName, ex);
                &#125;
            &#125;
        &#125;
        catch (BeansException ex) &#123;
            beanCreation.tag(&quot;exception&quot;, ex.getClass().toString());
            beanCreation.tag(&quot;message&quot;, String.valueOf(ex.getMessage()));
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        &#125;
        finally &#123;
            beanCreation.end();
        &#125;
    &#125;
    return adaptBeanInstance(name, beanInstance, requiredType);
&#125;
</code></pre>
<blockquote>
<p>doGetBean整体分为3个部分：</p>
</blockquote>
<p>1、根据Bean名字获取单例对象<br>2、判断获取单例对象是否为空<br>3、判断最后得到的Bean对象是否为要的类型</p>
<h3 id="Singleton初始化"><a href="#Singleton初始化" class="headerlink" title="Singleton初始化"></a>Singleton初始化</h3><pre><code class="java">//获取单例对象 三级缓存 解决循环依赖 后续文章会单独介绍
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) &#123;
    // Quick check for existing instance without full singleton lock
    // 检查singletonObjects中是否能获取到
    Object singletonObject = this.singletonObjects.get(beanName);
    //如果为null且当前的单例的bean正在创建过程中
    if (singletonObject == null &amp;&amp; isSingletonCurrentlyInCreation(beanName)) &#123;
        //从早期单例bean缓存中去获取
        singletonObject = this.earlySingletonObjects.get(beanName);
        //如果为null,且提前创建
        if (singletonObject == null &amp;&amp; allowEarlyReference) &#123;
            //锁定该全局变量singletonObjects进行相关的处理
            synchronized (this.singletonObjects) &#123;
                // Consistent creation of early reference within full singleton lock
                //从单例工厂中获取
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) &#123;
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null) &#123;
                    ObjectFactory&lt;?&gt; singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) &#123;
                        //调用getObject并获取对应的实例
                        singletonObject = singletonFactory.getObject();
                        //保存到earlySingletonObjects缓存中
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        //同时移除singletonFactories中的对应的objectFactory
                        this.singletonFactories.remove(beanName);
                    &#125;
                &#125;
            &#125;
        &#125;
    &#125;
&#125;
//如果从singletonObjects获取到了直接返回，不重复创建
return singletonObject;
&#125;
</code></pre>
<blockquote>
<p>getSingleton整体分为4个部分：</p>
</blockquote>
<p>1、从singletonObjects获取bean；<br>2、如果没拿到且当前bean正在创建中，从earlySingletonObjects中获取bean；<br>3、还是没拿到且运行提早创建，从singletonFactories中获取bean；<br>4、若不为null，则调用getObject()方法创建bean对象，并保存到earlySingletonObjects中，同时将自身中的objectFactory移除；</p>
<pre><code class="bash">singletonObjects:用于保存BeanName和创建bean实例之间的关系,即bean name---------------&gt;bean instance
earlySingletonObjects:用于保存BeanName和创建bean的实例之间的关系,与singletonObjects不同的是,当我们的bean存放到该缓存中后,如果当bean还在创建的过程中,直接可以通过getBean方法获取到了,主要还是对循环引用的检测,这也是为什么allowEarlyReference参数为true的原因.
singletonFactories用于保存beanName和创建的bean的工厂之间的关系.即-beanName------------&gt;ObjectFactory
</code></pre>
<blockquote>
<p>如果从doGetBean中Object sharedInstance = getSingleton(beanName)没有获取到bean。<br>对IOC容器中是否存在指定名称的BeanDefinition进行检查，首先检查是否能在当前的BeanFactory中获取的所需要的Bean，如果不能则委托当前容器的父级容器去查找，如果还是找不到则沿着容器的继承体系向父级容器查找</p>
</blockquote>
<pre><code class="java">//对IOC容器中是否存在指定名称的BeanDefinition进行检查，首先检查是否能
//在当前的BeanFactory中获取的所需要的Bean，如果不能则委托当前容器的父级
//容器去查找，如果还是找不到则沿着容器的继承体系向父级容器查找
BeanFactory parentBeanFactory = getParentBeanFactory();
//当前容器的父级容器存在，且当前容器不存在指定名称Bean
if (parentBeanFactory != null &amp;&amp; !containsBeanDefinition(beanName)) &#123;
    // Not found -&gt; check parent.
    //解析指定Bean名称的原始名称
    String nameToLookup = originalBeanName(name);
    if (parentBeanFactory instanceof AbstractBeanFactory abf) &#123;
        return abf.doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
    &#125;
    else if (args != null) &#123;
        // Delegation to parent with explicit args.
        //委派父级容器根据指定名称和显示的参数查找
        return (T) parentBeanFactory.getBean(nameToLookup, args);
    &#125;
    else if (requiredType != null) &#123;
        // No args -&gt; delegate to standard getBean method.
        //委派父级容器根据指定名称和类型查找
        return parentBeanFactory.getBean(nameToLookup, requiredType);
    &#125;
    else &#123;
        //委派父级容器根据指定名称和类型查找
        return (T) parentBeanFactory.getBean(nameToLookup);
    &#125;
&#125;
</code></pre>
<p>//TODO</p>
<pre><code class="java">final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) &#123;
    for (String dep : dependsOn) &#123;
        if (isDependent(beanName, dep)) &#123;
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    &quot;Circular depends-on relationship between &#39;&quot; + beanName + &quot;&#39; and &#39;&quot; + dep + &quot;&#39;&quot;);
        &#125;
        registerDependentBean(dep, beanName);
        try &#123;
            getBean(dep);
        &#125;
        catch (NoSuchBeanDefinitionException ex) &#123;
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    &quot;&#39;&quot; + beanName + &quot;&#39; depends on missing bean &#39;&quot; + dep + &quot;&#39;&quot;, ex);
        &#125;
    &#125;
&#125;
</code></pre>
<blockquote>
<p>创建单例模式Bean的实例对象</p>
</blockquote>
<pre><code class="java">//这里使用了一个匿名内部类，创建Bean实例对象，并且注册给所依赖的对象
sharedInstance = getSingleton(beanName, () -&gt; &#123;
    try &#123;
        //创建一个指定Bean实例对象，如果有父级继承，则合并子类和父类
        return createBean(beanName, mbd, args);
    &#125;
    catch (BeansException ex) &#123;
        // Explicitly remove instance from singleton cache: It might have been put there
        // eagerly by the creation process, to allow for circular reference resolution.
        // Also remove any beans that received a temporary reference to the bean.
        //显示的从容器单例模式Bean缓存中清除实例对象
        destroySingleton(beanName);
        throw ex;
    &#125;
&#125;);
//获取给定Bean实例对象
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
</code></pre>
<blockquote>
<p>AbstractAutowireCapableBeanFactory:createBean</p>
</blockquote>
<pre><code class="java">//创建Bean实例对象
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException &#123;
    if (logger.isTraceEnabled()) &#123;
        logger.trace(&quot;Creating instance of bean &#39;&quot; + beanName + &quot;&#39;&quot;);
    &#125;
    RootBeanDefinition mbdToUse = mbd;
    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    //判断需要创建的Bean是否可以实例化，即是否可以通过当前的类加载器加载
    Class&lt;?&gt; resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null &amp;&amp; !mbd.hasBeanClass() &amp;&amp; mbd.getBeanClassName() != null) &#123;
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    &#125;
    // Prepare method overrides.
    try &#123;
        //检验和准备Bean中的方法覆盖
        mbdToUse.prepareMethodOverrides();
    &#125;
    catch (BeanDefinitionValidationException ex) &#123;
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                    beanName, &quot;Validation of method overrides failed&quot;, ex);
    &#125;
    try &#123;
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        //如果Bean配置了初始化前和初始化后的处理器，则试图返回一个需要创建Bean的代理对象
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) &#123;
            return bean;
        &#125;
    &#125;
    catch (Throwable ex) &#123;
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                    &quot;BeanPostProcessor before instantiation of bean failed&quot;, ex);
    &#125;
    try &#123;
        //创建Bean的入口
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) &#123;
                logger.trace(&quot;Finished creating instance of bean &#39;&quot; + beanName + &quot;&#39;&quot;);
        &#125;
        return beanInstance;
    &#125;
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) &#123;
        // A previously detected exception with proper bean creation context already,
        // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
        throw ex;
    &#125;
    catch (Throwable ex) &#123;
        throw new BeanCreationException(
                    mbdToUse.getResourceDescription(), beanName, &quot;Unexpected exception during bean creation&quot;, ex);
    &#125;
&#125;
</code></pre>
<blockquote>
<p>doCreateBean通过三个步骤实例化Bean对象</p>
</blockquote>
<p>1、createBeanInstance()：创建Bean对象，方法内调用instantiateBean()方法中可以看出默认通过Cglib根据Deanfinition来进行实例化的。<br>2、populateBean()：为Bean进行参数初始化和属性赋值。<br>3、initializeBean()：初始化Bean实例和执行Bean的后置处理器。</p>
<pre><code class="java">//正在创建Bean的方法
    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException &#123;

        // Instantiate the bean.
        //封装被创建的Bean对象（不是真正的Bena）
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) &#123; //单例模式的Bean，先从容器缓存中获取同名Bean
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        &#125;
        if (instanceWrapper == null) &#123;
            //创建实例对象
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        &#125;
        Object bean = instanceWrapper.getWrappedInstance();
        //获取实例化对象的类型
        Class&lt;?&gt; beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) &#123;
            mbd.resolvedTargetType = beanType;
        &#125;

        // Allow post-processors to modify the merged bean definition.
        //调用PostProcessor后置处理器
        synchronized (mbd.postProcessingLock) &#123;
            if (!mbd.postProcessed) &#123;
                try &#123;
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                &#125;
                catch (Throwable ex) &#123;
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            &quot;Post-processing of merged bean definition failed&quot;, ex);
                &#125;
                mbd.markAsPostProcessed();
            &#125;
        &#125;

        // Eagerly cache singletons to be able to resolve circular references
        // even when triggered by lifecycle interfaces like BeanFactoryAware.
        //向容器中缓存单例模式的Bean对象，以防循环引用
        boolean earlySingletonExposure = (mbd.isSingleton() &amp;&amp; this.allowCircularReferences &amp;&amp;
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) &#123;
            if (logger.isTraceEnabled()) &#123;
                logger.trace(&quot;Eagerly caching bean &#39;&quot; + beanName +
                        &quot;&#39; to allow for resolving potential circular references&quot;);
            &#125;
            //这里是一个匿名内部类，为了防止循环引用，尽早持有对象的引用
            addSingletonFactory(beanName, () -&gt; getEarlyBeanReference(beanName, mbd, bean));
        &#125;

        // Initialize the bean instance.
        //Bean对象初始化，依赖注入在此触发
        //这个exposedObject在初始化完成之后返回作为依赖注入完成后的Bean
        Object exposedObject = bean;
        try &#123;
            //将Bean实例对象封装，并且Bean定义中配置的属性值赋值给实例对象
            populateBean(beanName, mbd, instanceWrapper);
            //初始化Bean对象
            //在对Bean实例对象生成和依赖注入完成以后，开始对Bean实例对象
            //进行初始化，为Bean实例对象应用BeanPostProcessor后置处理器
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        &#125;
        catch (Throwable ex) &#123;
            if (ex instanceof BeanCreationException &amp;&amp; beanName.equals(((BeanCreationException) ex).getBeanName())) &#123;
                throw (BeanCreationException) ex;
            &#125;
            else &#123;
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, ex.getMessage(), ex);
            &#125;
        &#125;

        if (earlySingletonExposure) &#123;
            //获取指定名称的已注册的单例模式Bean对象
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) &#123;
                //根据名称获取的已注册的Bean和正在实例化的Bean是同一个
                if (exposedObject == bean) &#123;
                    //当前实例化的Bean初始化完成
                    exposedObject = earlySingletonReference;
                &#125;
                //当前Bean依赖其他Bean，并且当发生循环引用时不允许新创建实例对象
                else if (!this.allowRawInjectionDespiteWrapping &amp;&amp; hasDependentBean(beanName)) &#123;
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set&lt;String&gt; actualDependentBeans = new LinkedHashSet&lt;&gt;(dependentBeans.length);
                    //获取当前Bean所依赖的其他Bean
                    for (String dependentBean : dependentBeans) &#123;
                        //对依赖Bean进行类型检查
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) &#123;
                            actualDependentBeans.add(dependentBean);
                        &#125;
                    &#125;
                    if (!actualDependentBeans.isEmpty()) &#123;
                        throw new BeanCurrentlyInCreationException(beanName,
                                &quot;Bean with name &#39;&quot; + beanName + &quot;&#39; has been injected into other beans [&quot; +
                                StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                &quot;] in its raw version as part of a circular reference, but has eventually been &quot; +
                                &quot;wrapped. This means that said other beans do not use the final version of the &quot; +
                                &quot;bean. This is often the result of over-eager type matching - consider using &quot; +
                                &quot;&#39;getBeanNamesForType&#39; with the &#39;allowEagerInit&#39; flag turned off, for example.&quot;);
                    &#125;
                &#125;
            &#125;
        &#125;

        // Register bean as disposable.
        try &#123;
            //注册完成依赖注入的Bean
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        &#125;
        catch (BeanDefinitionValidationException ex) &#123;
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, &quot;Invalid destruction signature&quot;, ex);
        &#125;

        return exposedObject;
    &#125;
</code></pre>
<blockquote>
<p>createBeanInstance定义Bean实例化形式有几种</p>
</blockquote>
<p>1、使用工厂方法对Bean进行实例化<br>2、使用容器的自动装配方法进行实例化<br>3、使用Bean的构造方法进行实例化<br>4、使用默认的构造方法实例化</p>
<pre><code class="java">//创建Bean的实例对象
    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) &#123;
        // Make sure bean class is actually resolved at this point.
        //检查确认Bean是可实例化的
        Class&lt;?&gt; beanClass = resolveBeanClass(mbd, beanName);
        //使用工厂方法对Bean进行实例化
        if (beanClass != null &amp;&amp; !Modifier.isPublic(beanClass.getModifiers()) &amp;&amp; !mbd.isNonPublicAccessAllowed()) &#123;
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    &quot;Bean class isn&#39;t public, and non-public access not allowed: &quot; + beanClass.getName());
        &#125;

        Supplier&lt;?&gt; instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) &#123;
            return obtainFromSupplier(instanceSupplier, beanName);
        &#125;

        if (mbd.getFactoryMethodName() != null) &#123;
            //调用工厂方法实例化
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        &#125;

        // Shortcut when re-creating the same bean...
        //使用容器的自动装配方法进行实例化
        boolean resolved = false;
        boolean autowireNecessary = false;
        if (args == null) &#123;
            synchronized (mbd.constructorArgumentLock) &#123;
                if (mbd.resolvedConstructorOrFactoryMethod != null) &#123;
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                &#125;
            &#125;
        &#125;
        if (resolved) &#123;
            if (autowireNecessary) &#123;
                //配置了自动装配属性，使用容器的自动装配实例化
                //容器的自动装配是根据参数类型匹配Bean的构造方法
                return autowireConstructor(beanName, mbd, null, null);
            &#125;
            else &#123;
                //使用默认的无参构造方法实例化
                return instantiateBean(beanName, mbd);
            &#125;
        &#125;

        // Candidate constructors for autowiring?
        //使用Bean的构造方法进行实例化
        Constructor&lt;?&gt;[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) &#123;
            //使用容器的自动装配特性，调用匹配的构造方法实例化
            return autowireConstructor(beanName, mbd, ctors, args);
        &#125;

        // Preferred constructors for default construction?
        ctors = mbd.getPreferredConstructors();
        if (ctors != null) &#123;
            return autowireConstructor(beanName, mbd, ctors, null);
        &#125;

        // No special handling: simply use no-arg constructor.
        //使用默认的午餐构造方法实例化
        return instantiateBean(beanName, mbd);
    &#125;
</code></pre>
<blockquote>
<p>分析使用默认的构造方法实例化</p>
</blockquote>
<p>通过动态代理生成的实例使用BeanWrapper进行保存</p>
<pre><code class="java">//使用默认的无参构造方法实例化Bean对象
    protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) &#123;
        try &#123;
            //将实例化的对象封装起来
            Object beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
            BeanWrapper bw = new BeanWrapperImpl(beanInstance);
            initBeanWrapper(bw);
            return bw;
        &#125;
        ...省略...
    &#125;
</code></pre>
<blockquote>
<p>JDK动态代理与CGLIB代理选择</p>
</blockquote>
<p>如果Bean定义中没有方法覆盖，没有实现AbstractBeanDefinition，则就不需要CGLIB父类类的方法<br>Spring AOP 默认为 AOP 代理使用标准的 JDK 动态代理。这允许代理任何接口（或接口集）。<br>Spring AOP 也可以使用 CGLIB 代理。这是代理类而不是接口所必需的。默认情况下，如果业务对象未实现接口，则使用 CGLIB。</p>
<pre><code class="java">//使用初始化策略实例化Bean对象
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) &#123;
   // Don&#39;t override the class with CGLIB if no overrides.
   //如果Bean定义中没有方法覆盖，没有实现AbstractBeanDefinition，则就不需要CGLIB父类类的方法
   //Spring AOP 默认为 AOP 代理使用标准的 JDK 动态代理。这允许代理任何接口（或接口集）。
   //Spring AOP 也可以使用 CGLIB 代理。这是代理类而不是接口所必需的。默认情况下，如果业务对象未实现接口，则使用 CGLIB。
   if (!bd.hasMethodOverrides()) &#123;
      Constructor&lt;?&gt; constructorToUse;
      synchronized (bd.constructorArgumentLock) &#123;
         //获取对象的构造方法或工厂方法
         constructorToUse = (Constructor&lt;?&gt;) bd.resolvedConstructorOrFactoryMethod;
         //如果没有构造方法且没有工厂方法
         if (constructorToUse == null) &#123;
            //使用JDK的反射机制，判断要实例化的Bean是否是接口
            final Class&lt;?&gt; clazz = bd.getBeanClass();
            if (clazz.isInterface()) &#123;
               throw new BeanInstantiationException(clazz, &quot;Specified class is an interface&quot;);
            &#125;
            try &#123;
               //通过发射机制获取Bean的构造方法
               constructorToUse = clazz.getDeclaredConstructor();
               bd.resolvedConstructorOrFactoryMethod = constructorToUse;
            &#125;
            catch (Throwable ex) &#123;
               throw new BeanInstantiationException(clazz, &quot;No default constructor found&quot;, ex);
            &#125;
         &#125;
      &#125;
      //使用BeanUtils实例化，通过发射机制调用“构造方法.newInstance(arg)”来进行实例化
      return BeanUtils.instantiateClass(constructorToUse);
   &#125;
   else &#123;
      // Must generate CGLIB subclass.
      //使用CGLIB来实例化对象
      return instantiateWithMethodInjection(bd, beanName, owner);
   &#125;
&#125;
</code></pre>
<blockquote>
<p>AbstractAutowireCapableBeanFactory::populateBean</p>
</blockquote>
<p>根据autowire类型进行autowire by name，by type 或者是直接进行设置</p>
<pre><code class="java">//将Bean属性设置到生成的实例对象上
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) &#123;
   //实例对象为null
   if (bw == null) &#123;
      //获取容器在解析Bean定义资源时BeanDefinition中设置的属性值
      if (mbd.hasPropertyValues()) &#123;
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, &quot;Cannot apply property values to null instance&quot;);
      &#125;
      else &#123;
         // Skip property population phase for null instance.
         //实例对象为null，属性值也为空，不需要设置属性值，直接返回
         return;
      &#125;
   &#125;

   // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
   // state of the bean before properties are set. This can be used, for example,
   // to support styles of field injection.
   if (!mbd.isSynthetic() &amp;&amp; hasInstantiationAwareBeanPostProcessors()) &#123;
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;
         if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) &#123;
            return;
         &#125;
      &#125;
   &#125;

   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

   int resolvedAutowireMode = mbd.getResolvedAutowireMode();
   //依赖注入开始，首先处理autowire自定装配的注入
   if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) &#123;
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      // Add property values based on autowire by name if applicable.
      //对autowire自动装配的处理，根据Bean的名称自动装配注入
      if (resolvedAutowireMode == AUTOWIRE_BY_NAME) &#123;
         autowireByName(beanName, mbd, bw, newPvs);
      &#125;
      // Add property values based on autowire by type if applicable.
      //根据Bean类型自动装配注入
      if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) &#123;
         autowireByType(beanName, mbd, bw, newPvs);
      &#125;
      pvs = newPvs;
   &#125;
   //检查容器是否持有用于处理单例模式Bean关闭时的后置处理器
   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   //Bean实例对象没有依赖，即没有继承基类
   boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

   if (hasInstAwareBpps) &#123;
      if (pvs == null) &#123;
         pvs = mbd.getPropertyValues();
      &#125;
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;
         PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
         if (pvsToUse == null) &#123;
            return;
         &#125;
         pvs = pvsToUse;
      &#125;
   &#125;
   if (needsDepCheck) &#123;
      //从实例对象中提取属性描述符
      PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      //为要设置的属性进行依赖检查
      checkDependencies(beanName, mbd, filteredPds, pvs);
   &#125;

   if (pvs != null) &#123;
      //对属性进行注入
      applyPropertyValues(beanName, mbd, bw, pvs);
   &#125;
&#125;
</code></pre>
<h3 id="Prototype初始化"><a href="#Prototype初始化" class="headerlink" title="Prototype初始化"></a>Prototype初始化</h3><pre><code class="java">if (mbd.isPrototype()) &#123;
   // It&#39;s a prototype -&gt; create a new instance.
   //原型模式（Prototype）是每次都会创建一个新的对象
   Object prototypeInstance = null;
   try &#123;
      //回调beforePrototypeCreation方法，默认的功能是注册当前创建的原型对象
      beforePrototypeCreation(beanName);
      //创建指定Bean对象实例
      prototypeInstance = createBean(beanName, mbd, args);
   &#125;
   finally &#123;
      //回调afterPrototypeCreation方法，默认的功能告诉IOC容器指定Bean
      afterPrototypeCreation(beanName);
   &#125;
   //获取给定Bean的实例对象
   beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
&#125;
</code></pre>
<pre><code class="java">protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) &#123;
   invokeAwareMethods(beanName, bean);

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) &#123;
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   &#125;

   try &#123;
      invokeInitMethods(beanName, wrappedBean, mbd);
   &#125;
   catch (Throwable ex) &#123;
      throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null), beanName, ex.getMessage(), ex);
   &#125;
   if (mbd == null || !mbd.isSynthetic()) &#123;
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   &#125;

   return wrappedBean;
&#125;
</code></pre>
</article><section class="jump-container is-flex is-justify-content-space-between my-6"><!-- em is empty placeholder--><a class="button is-default" href="/blog/2022/11/29/Spring/Spring%E6%89%A9%E5%B1%95%E5%8A%9F%E8%83%BD-BeanDefinitionRegistryPostProcessor/" title="【Spring源码解析系列】 BeanDefinitionRegistryPostProcessor"><i class="iconfont icon-prev mr-2 has-text-grey"></i><span class="has-text-weight-semibold">上一页: 【Spring源码解析系列】 BeanDefinitionRegistryPostProcessor</span></a><a class="button is-default" href="/blog/2022/09/23/SQL/SQLite-UPDATE%E5%91%BD%E4%BB%A4%E6%89%A7%E8%A1%8C%E8%AE%A1%E5%88%92/" title="【手撕SQL】SQLite UPDATE 命令执行计划"><span class="has-text-weight-semibold">下一页: 【手撕SQL】SQLite UPDATE 命令执行计划</span><i class="iconfont icon-next ml-2 has-text-grey"></i></a></section><article class="mt-6 comment-container"><script async repo="janedler/blog" src="https://utteranc.es/client.js" issue-term="pathname" theme="preferred-color-scheme"></script></article></div></div></main></main><footer class="is-flex is-flex-direction-column is-align-items-center is-flex-shrink-0 is-family-serif"><section class="sns-container"><!-- Github--><a title="github" target="_blank" rel="noopener nofollow" href="//github.com//janedler"><i class="iconfont icon-github"></i></a><!-- Ins--><!-- RSS--><a title="rss" target="_blank" rel="noopener nofollow" href="/blog/atom.xml"><i class="iconfont icon-rss"></i></a><!-- 知乎--><!-- 领英--><!-- 脸书--></section><p><span>Copyright ©</span><span> 田园牧歌(*︶*) 2022</span></p><div class="is-flex is-justify-content-center is-flex-wrap-wrap"><p>Powered by Hexo &verbar;&nbsp;</p><p class="is-flex is-justify-content-center"><a title="Hexo theme author" target="_blank" rel="noopener" href="//github.com/haojen">Theme by Haojen&nbsp;</a></p><div style="margin-top: 2px"><a class="github-button" title="github-button" target="_blank" rel="noopener" href="https://github.com/haojen/hexo-theme-Claudia" data-color-scheme="no-preference: light; light: light; dark: dark;" data-show-count="true"></a></div></div><div><span></span></div></footer><script async defer src="https://buttons.github.io/buttons.js"></script><script src="/blog/js/post.js"></script></body></html>